<script lang="ts" setup>
import { ResourceParam } from "@/common/apis/file/type";
import { uploadBase64 } from "@/common/apis/file/index";
import { Delete, Plus } from "@element-plus/icons-vue";
import type { UploadFile, UploadProps, UploadRequestOptions } from "element-plus";
import { ref, onMounted } from "vue";
import { fileToBase64, getFullUrl } from "../../utils/file";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

// 父组件传过来的值
let props = defineProps({
  imageUrl: {
    type: String,
    default: () => {
      console.log("props-imageUrl", this);
    },
  },
  formData: {
    type: Object,
    default: () => {
      console.log("props-formData", this);
    },
  },
  updateUrl: {
    type: Function,
  },
});

// 向父组件暴露方法
defineExpose({
  clear() {
    imageList.value = [];
    console.log("upload-child-clear", imageList.value);
  },
  showInfo() {
    console.log("upload-child-showInfo", imageList.value);
  },
});

onMounted(() => {
  console.log("imageList: ", imageList.value);
  if (props.imageUrl === "" || props.imageUrl === null || props.imageUrl === undefined) {
    return;
  }
  // imageList.value.push({
  //   name: "img",
  //   url: getFullUrl(props.imageUrl),
  // });
  console.log("upload-child-onMounted", imageList.value);
});

// 图片绑定数据
const imageList = ref<UploadFile[]>([]);

const handleRemove = (uploadFile: UploadFile) => {
  const index = imageList.value.findIndex((file) => file.uid === uploadFile.uid);
  if (index !== -1) {
    imageList.value.splice(index, 1); // 手动移除文件
  }
  console.log("图片列表", imageList.value);
  console.log("文件已移除，执行其他操作...");
};

const handleSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  // formData.value.mainImage = URL.createObjectURL(uploadFile.raw!);
  // console.log(formData.value.mainImage);
};

const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  // 此处做一次清理，避免控制台报错
  imageList.value=[]
  fileToBase64(uploadFile.raw).then((base64) => {
    const body = new ResourceParam(0, uploadFile.name, base64);

    uploadBase64(body)
      .then((result) => {
        console.log("url: " + result.data.url);
        // 清空列表，避开组件自动添加的资源
        imageList.value=[]
        // 将上传成功的图片连接加入列表
        imageList.value.push({
          name: "img",
          url: getFullUrl(result.data.url),
        });
        console.log("imageList: " + JSON.stringify(imageList.value));
        props.updateUrl(result.data.url);
      })
      .catch((err) => {
        console.log(err);
      });
  });
};

</script>

<template>
  <!-- 当 imageList 为空时，渲染 el-upload -->
  <el-upload
    v-if="imageList.length === 0"
    v-model:file-list="imageList"
    action="#"
    list-type="picture-card"
    :multiple="false"
    :limit="1"
    :auto-upload="false"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    :on-change="handleChange"
    :on-remove="handleRemove"
  >
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>

  <!-- 当 imageList 不为空时，显示已上传的图片和删除按钮 -->
  <div v-else class="custom-picture-card">
    <img class="el-upload-list__item-thumbnail" :src="imageList[0].url" alt="" />
    <span class="el-upload-list__item-actions">
      <span class="el-upload-list__item-delete" @click="handleRemove(imageList[0])">
        <el-icon>
          <Delete />
        </el-icon>
      </span>
    </span>
  </div>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<style scoped>
.custom-picture-card {
  position: relative;
  width: 148px; /* 与 picture-card 的默认尺寸一致 */
  height: 148px;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  overflow: hidden;
}

.custom-picture-card img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.el-upload-list__item-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.custom-picture-card:hover .el-upload-list__item-actions {
  opacity: 1;
}

/* 删除按钮样式 */
.el-upload-list__item-delete {
  cursor: pointer;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.3s;
  font-size: 24px; /* 调整图标大小 */
  width: 32px; /* 按钮宽度 */
  height: 32px; /* 按钮高度 */
  border-radius: 50%; /* 圆形按钮 */
  background-color: rgba(0, 0, 0, 0.6); /* 按钮背景色 */
}

.el-upload-list__item-delete:hover {
  color: #f7a31c; /* 悬停时改变图标颜色 */
  background-color: rgba(0, 0, 0, 0.8); /* 悬停时加深背景色 */
}
</style>
